<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */

    /*********************************************************
    *            --== InArch ==--
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @since 01.05.2005
    * @copyright essentialmind.com 2005
    *
    *********************************************************/

    /***
    * Class fileUploader
    ****
    * This class will upload files and imager to designated directories,
    * images will be resized to create thumbnails.
    ****
    * @package usefulStuff
    * @author A Kulikov <a.kulikov@gmail.com>
    * @version n/a
    * @since 01.05.2005
    * @copyright essentialmind.com 2005
    ***/
    class fileUploader{
        /**
         * Whether UNIX imageMagick is applied for resizing instead of GD2
         *
         * @var bool
         */
        private $useIMagick;

		/**
		 * Constructor
		 *
		 * @return void
		 */
		public function __construct(){
            $this->useIMagick = $GLOBALS['_CONFIG']['use_imagick'];
		}


		/**
		 * Check if the file to be uploaded in a jpeg
		 *
		 * @param string $filename
		 * @return array or false
		 */
		public function isJPEG($filename){
			$size = @getimagesize($filename);
			if($size[2]==2){
				return $size;
			}
			return false;
		}


		/**
		 * Check if the file is an image
		 *
		 * @param string $filename
		 * @return bool
		 */
		public function isImage($filename){
			return getimagesize($filename);
		}


		/**
		 * Wrapper to decide between resizing image or not
		 *
		 * @param string $name
		 * @param string $destination
		 * @param integer $width
		 * @param integer $height
		 * @return bool
		 */
		public function copyJPEG($name,$destination,$width=800,$height=600){
			$width = (int)$width;
			$height = (int)$height;

			//check if destination file exists
			if(file_exists($destination)){
			    unlink($destination);
			}

			if(!$this->isImage($name)){
				return false;
			}else{
				if(!$this->useIMagick){
					return $this->resize_jpeg($name,$destination,$width,$height);
				}else{
					return $this->resize($name,$destination,$width,$height);
				}
			}
		}



		/**
		 * Actual file uploader
		 *
		 * @param string $name
		 * @param string $destination
		 * @return bool
		 */
		public function copyFile($name,$destination){
			if(!$result = move_uploaded_file($name,$destination)){
				$result = copy($name,$destination);
			}
			return $result;
		}


		/**
		 * Resizes jpeg files without ImageMagick but with GD2
		 *
		 * @param string $image_file_path
		 * @param string $new_image_file_path
		 * @param integer $max_width
		 * @param integer $max_height
		 * @return
		 */
		protected function resize_jpeg($image_file_path, $new_image_file_path, $max_width, $max_height){
    		$return_val = 1;

    		$return_val = ( ($img = ImageCreateFromJPEG ( $image_file_path )) && $return_val == 1 ) ? "1" : "0";

    		$FullImage_width  = imagesx ($img);    // Original image width
    		$FullImage_height = imagesy ($img);    // Original image height

    		// now we check for over-sized images and pare them down
    		// to the dimensions we need for display purposes
    		$ratio =  ( $FullImage_width > $max_width ) ? (real)($max_width / $FullImage_width) : 1 ;
    		$new_width = ((int)($FullImage_width * $ratio));    //full-size width
    		$new_height = ((int)($FullImage_height * $ratio));    //full-size height

			//check for images that are still too high
    		$ratio =  ( $new_height > $max_height ) ? (real)($max_height / $new_height) : 1 ;
    		$new_width = ((int)($new_width * $ratio));    //mid-size width
    		$new_height = ((int)($new_height * $ratio));    //mid-size height

    		// --Start Full Creation, Copying--
    		// now, before we get silly and 'resize' an image that doesn't need it...
    		if ( $new_width == $FullImage_width && $new_height == $FullImage_height )
       			copy ( $image_file_path, $new_image_file_path );

    		$full_id = ImageCreateTrueColor( $new_width , $new_height );        //create an image
    		ImageCopyResized( $full_id, $img,
      		              0,0,  0,0, //starting points
          		          $new_width, $new_height,
              		      $FullImage_width, $FullImage_height );

    		$return_val = ( $full = ImageJPEG( $full_id, $new_image_file_path, 80) && $return_val == 1 ) ? "1" : "0";
    		ImageDestroy( $full_id );

    		// --End Creation, Copying--
    		return ($return_val) ? TRUE : FALSE;
		}



        public function createSquare($source,$dest,$thumb_size=150) {
            $size = getimagesize($source);
            $width = $size[0];
            $height = $size[1];
            if($width> $height) {
                $x = ceil(($width - $height) / 2 );
                $width = $height;
            } elseif($height> $width) {
                $y = ceil(($height - $width) / 2);
                $height = $width;
            }
            $new_im = ImageCreatetruecolor($thumb_size,$thumb_size);
         
            $im = imagecreatefromjpeg($source);
            imagecopyresampled($new_im,$im,0,0,$x,$y,$thumb_size,$thumb_size,$width,$height);
            imagejpeg($new_im,$dest,100);
        }


		/**
		 * imageMagick resizer
		 *
		 * THIS NEEDS REFACTORING!!!!!!!!!!!!!!!!!!!!!!!
		 *
		 * @param string $image_file_path
		 * @param string $new_image_file_path
		 * @param integer $max_width
		 * @param integer $max_height
		 * @return void
		 **/
		protected function resize($image_file_path, $new_image_file_path, $max_width, $max_height){
			$sizes = getimagesize($image_file_path);
			$FullImage_width = $sizes[0];
			$FullImage_height = $sizes[1];

			// now we check for over-sized images and pare them down
    		// to the dimensions we need for display purposes
			$ratio =  ( $FullImage_width > $max_width ) ? (real)($max_width / $FullImage_width) : 1 ;
    		$new_width = ((int)($FullImage_width * $ratio));    //full-size width
    		$new_height = ((int)($FullImage_height * $ratio));  //full-size height

			//check for images that are still too high
    		$ratio =  ( $new_height > $max_height ) ? (real)($max_height / $new_height) : 1 ;
    		$new_width = ((int)($new_width * $ratio));    //mid-size width
    		$new_height = ((int)($new_height * $ratio));  //mid-size height

			// now, before we get silly and 'resize' an image that doesn't need it...
			$reply = system("convert -resize " . $new_width . "x" . $new_height . " " . $image_file_path . " " . $new_image_file_path);
		}


        //this function is a system specific tweak, it NEEDS REFACTORING
        public function mark($image,$text){
            if($this->useIMagick){
                system("convert -font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf -pointsize 12 -gravity SouthEast -fill black -draw \"text 10,10 '".$text."'\"  -fill white -draw \"text 11,11 '".$text."'\" ".$image." ".$image);
            }
        }


        /***
         *  Drop Image Shadow
         ***/
        public function createShadow($source, $dest, $z1=40, $z2=5, $x=0, $y=10){
            if($this->useIMagick){
//                echo "convert ".$source." \( +clone -background black -shadow ".$z1."x".$z2."+".$x."+".$y." \) +swap -background none -layers merge +repage ".$dest;exit;
                system("convert ".$source." \( +clone -background black -shadow ".$z1."x".$z2."+".$x."+".$y." \) +swap -background none -layers merge +repage ".$dest);
            }
        }


		/**
		 * Check if the desired path exists, if not, create it
		 *
		 * @param string $uploadPath 	-- actual path to be checked for existence
		 * @param integer $chmod		-- default chmod for the directory created
		 * @return bool
		 **/
		public function preparePath($uploadPath, $chmod = 0777){
		        //echo $uploadPath; exit;

		        $uploadPath = str_replace(ROOT,'',$uploadPath);

	   		//check if directory exists, if not, attempt to create it
			if(!is_dir($uploadPath)){

			    try{
    			    //explode the whole path into compontents
    			    $tempPathArray   = explode(DIRECTORY_SEPARATOR,$uploadPath);
    			    $tempPath        = null;

    			    //cycle through the array attempting to create anything that does not exist
    			    foreach($tempPathArray as $directory){
                        $tempPath .= $directory . DIRECTORY_SEPARATOR;

                        if(!@is_dir($tempPath)){
                            @mkdir($tempPath, $chmod);
    				        @chmod($tempPath, $chmod);
                        }
    			    }

    			//we don't want to see tonns of errors
			    }catch(Exception $e){
			        return false;
			    }
			}

			return true;
		}

	}
?>
